import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import Minio from 'minio';

@Injectable()
export class LargeFileUploadService {
  constructor(private configService: ConfigService) {
    this.configService = configService;
  }
  // 上传文件到minio
  async uploadMinio(filePath: string) {
    try {
      const minioClient = new Minio.Client({
        endPoint:
          this.configService.get<string>('MINIO_ENDPOINT') || 'localhost',
        port: this.configService.get('MINIO_PORT')!,
        useSSL: this.configService.get<boolean>('MINIO_USE_SSL') || false,
        accessKey: this.configService.get('MINIO_ACCESS_KEY')!,
        secretKey: this.configService.get('MINIO_SECRET_KEY')!,
      });
      const bucketName = this.configService.get('MINIO_BUCKET'); // minio bucket名称
      // 确保存储桶存在
      const isExist = await minioClient.bucketExists(bucketName);
      if (!isExist) {
        throw new Error(`存储桶 ${bucketName} 不存在`);
      }

      await minioClient.fPutObject(bucketName, filePath, filePath);

      const protocol = this.configService.get<boolean>('MINIO_USE_SSL')
        ? 'https'
        : 'http';
      return `${protocol}://${this.configService.get('MINIO_ENDPOINT')}:${this.configService.get('MINIO_PORT')}/${bucketName}/${filePath}`;
    } catch (error) {
      console.error('MinIO上传失败:', error);
      throw new Error(`文件上传失败: ${error.message}`);
    }
  }
}
